package com.example.day19_7_19_1.util;

import com.example.day19_7_19_1.net.ApiService;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpUtil {
    private static volatile HttpUtil sHttpUtil = null;
    private Retrofit.Builder builder;

    private HttpUtil(){
        OkHttpClient okHttpClient = initOkHttp();
        initRetrofit(okHttpClient);
    }

    private void initRetrofit(OkHttpClient okHttpClient) {
        builder = new Retrofit.Builder()
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create());
    }

    private OkHttpClient initOkHttp() {
        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .addInterceptor(new LogInterceptor())
                .cache(new Cache(new File(Constants.PATH_CACHE),1024*1024*50))
                .build();
        return client;
    }

    volatile ApiService apiService = null;
    public ApiService getApiService(String itemUrl) {
        if (apiService == null){
            synchronized (HttpUtil.class){
                if (apiService == null){
                    apiService = builder.baseUrl(itemUrl)
                            .build()
                            .create(ApiService.class);
                }
            }
        }
        return apiService;
    }

    public class LogInterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            LogUtil.logd(response.peekBody(1024*1024*4).string());
            return response;
        }
    }

    public static HttpUtil getInstance(){
        if (sHttpUtil == null){
            synchronized (HttpUtil.class){
                if (sHttpUtil == null){
                    sHttpUtil = new HttpUtil();
                }
            }
        }
        return sHttpUtil;
    }
}
